<template>
  <div class="app-container">

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('Edit_Store_Details') }}</span>

        <el-button v-permission="['GET /admin/p/store_user_index']" style="float: right; padding: 3px 0" type="text"
                   @click="members()">{{ $t('View_partners_list') }}</el-button>
        <el-button v-permission="['GET /admin/p/store_oplog_index']"
                   style="float: right; padding: 3px 0;margin-right: 10px;" type="text" @click="handleLogs()">
          {{ $t('View_Journals') }}</el-button>
      </div>
      <el-form ref="shop" :rules="rules" :model="shop" label-width="150px">
        <el-form-item :label="$t('Store_name')" prop="name">
          <el-input v-model="shop.name" />
        </el-form-item>
        <el-form-item :label="$t('Store_color')" prop="name">
          <el-color-picker v-model="shop.color" :predefine="predefineColors"></el-color-picker>
        </el-form-item>
        <el-form-item :label="$t('Store_address')" prop="streetAddress">
          <el-input v-model="shop.streetAddress" />
        </el-form-item>
        <el-form-item :label="$t('税务编码')" prop="taxCode">
          <el-input v-model="shop.taxCode" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('Country')" prop="country">
              <el-select v-model="regionIds[0]" filterable @change="getPrivonces(true)" :placeholder="$t('请选择')">
                <el-option v-for="item in countrys" :label="item.nameCn || item.nameEn" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('Province')" prop="province">
              <el-select v-model="regionIds[1]" filterable @change="getCitys(true)" :placeholder="$t('请选择')">
                <el-option v-for="item in provinces" :label="item.nameCn || item.nameEn" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('City')" prop="city">
              <el-select v-model="regionIds[2]" filterable @change="getCountys(true)" :placeholder="$t('请选择')">
                <el-option v-for="item in citys" :label="item.nameCn || item.nameEn" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('区县')" prop="county" v-if="countys && countys.length > 0">
              <el-select v-model="regionIds[3]" filterable>
                <el-option v-for="item in countys" :label="item.nameCn || item.nameEn" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('Postal_ZIP')" prop="postalCode">
              <el-input v-model="shop.postalCode" />
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">
            <el-form-item :label="$t('地址')" prop="streetAddress">
              <el-input v-model="shop.streetAddress"/>
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item :label="$t('Unit')" prop="aptUnit">
              <el-input v-model="shop.aptUnit" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('Longitude')">
              <el-input v-model="shop.longitude" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('Latitude')">
              <el-input v-model="shop.latitude" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :label="$t('Store_Supervisor')" prop="shopManager">
          <el-tooltip class="item" effect="dark" :content="$t('Promotion from member list to store manager')" placement="top-start">
            <i style="color: #ee9900" class="el-icon-warning-outline"></i>
          </el-tooltip>
          <!--          <el-link  :value="shopMembers[0].id" :label="shopMembers[0].nickName" target="_blank">{{shopMembers[0].nickName}}</el-link>-->
          <el-select style="width: 500px;" v-model="shopManager.id" clearable
                     :placeholder="$t('Promotion from member list to store manager')" >
            <el-option v-for="item in shopMembers" :value="item.id" :label="item.nickName" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('Store_Manager')" prop="shopkeeper">
          <el-tooltip class="item" effect="dark" :content="$t('Change_account_to_store_manager_account_in_partner_list')" placement="top-start">
            <i style="color: #ee9900" class="el-icon-warning-outline"></i>
          </el-tooltip>
          <!--          <el-link type="primary" :value="shopMembers[0].id" :label="shopMembers[0].nickName" target="_blank">{{shopMembers[0].nickName}}</el-link>-->
          <el-select style="width: 500px;" v-model="shopkeeper.id" clearable :placeholder="$t('Change_account_to_store_manager_account_in_partner_list')"  >
            <el-option v-for="item in shopMembers" :value="item.id" :label="item.nickName" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('Contact_number')" prop="mobile">
          <el-input v-model="shop.mobile" placeholder="13000000000" />
        </el-form-item>
        <el-form-item :label="$t('营业时间')" prop="mobile">
          <el-popover
            @show="handleShow"
            placement="right"
            trigger="click">
            <el-descriptions class="margin-top" :title="$t('说明：如不开业请设置服务时间为 00:00:00-00:00:00')" :column="2" border>
              <el-descriptions-item v-for="o in 7" :span="1">
                <template slot="label">
                  <el-tag :style="{width:'80px','text-align':'center'}" type="info">{{weeksTimeMap[o] }}</el-tag>
                </template>
                <el-time-picker
                  format="HH:mm:ss" value-format="HH:mm:ss"
                  is-range
                  :clearable="false"
                  v-model="weeksTime[o-1]"
                  range-separator="-"
                  :start-placeholder="$t('开始时间')"
                  :end-placeholder="$t('结束时间')"
                  :placeholder="$t('选择时间')">
                </el-time-picker>
              </el-descriptions-item>
              <template slot="extra">
                <el-button type="primary" size="small" @click="showDatePicker"> {{!showDatepicker?$t('添加特殊日期'):$t('关闭') }}</el-button>
                <el-date-picker
                  :clearable="false"
                  value-format="yyyy-MM-dd"
                  @change="handleChangePicker"
                  v-model="selectedDate"
                  v-if="showDatepicker" >
                </el-date-picker>
              </template>
<!--              特殊日期-->
              <el-descriptions-item  v-for="o in this.special.length" :span="1">
                <template slot="label">
                  <el-tag effect="dark" type="warning">{{special[o-1].specialDate }}</el-tag>
                </template>
                <el-time-picker
                  format="HH:mm:ss" value-format="HH:mm:ss"
                  is-range
                  :clearable="false"
                  v-model="special[o-1].specialTime"
                  range-separator="-"
                  :start-placeholder="$t('开始时间')"
                  :end-placeholder="$t('结束时间')"
                  :placeholder="$t('选择时间')">
                </el-time-picker>
                <el-button :style="{'margin-left':'5px'}" @click="handleSpecialTimeDeleted(o-1)" size="mini" type="danger" icon="el-icon-delete" ></el-button>
              </el-descriptions-item>
            </el-descriptions>
            <el-button type="text" icon="el-icon-setting" slot="reference">{{$t('设置营业时间')}}</el-button>
          </el-popover>
        </el-form-item>
<!--        <el-form-item :label="$t('营业时间')" prop="mobile">
          <el-card shadow="hover" :style="{width:'1000px'}" class="box-card">
          <el-descriptions  class="margin-top" :title="$t('说明：如不开业请设置服务时间为 00:00:00-00:00:00')" :column="2" border>
            <el-descriptions-item v-for="o in 7" :span="1">
              <template slot="label">
                {{weeksTimeMap[o] }}
              </template>
              <el-time-picker
                format="HH:mm:ss" value-format="HH:mm:ss"
                is-range
                v-model="weeksTime[o-1]"
                range-separator="-"
                :start-placeholder="$t('开始时间')"
                :end-placeholder="$t('结束时间')"
                :placeholder="$t('选择时间范围')">
              </el-time-picker>
            </el-descriptions-item>
            <template slot="extra">
              <el-button type="primary" size="small" @click="showDatePicker"> {{!showDatepicker?$t('添加特殊日期'):$t('关闭') }}</el-button>
              <el-date-picker v-model="selectedDate" v-if="showDatepicker" ></el-date-picker>
            </template>
            <el-divider v-show="this.showDatepicker"></el-divider>
          </el-descriptions>
          </el-card>
        </el-form-item>-->
<!--        <el-form-item :label="$t('Business_Days')" prop="weeks">
          <el-checkbox-group v-model="shop.weeks">
            <el-checkbox :label="1">{{ $t('Monday') }}</el-checkbox>
            <el-checkbox :label="2">{{ $t('Tuesday') }}</el-checkbox>
            <el-checkbox :label="3">{{ $t('Wednesday') }}</el-checkbox>
            <el-checkbox :label="4">{{ $t('Thursday') }}</el-checkbox>
            <el-checkbox :label="5">{{ $t('Friday') }}</el-checkbox>
            <el-checkbox :label="6">{{ $t('Saturday') }}</el-checkbox>
            <el-checkbox :label="7">{{ $t('Sunday') }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('Service_hours')" prop="serviceTime">
          <el-col :span="6">
            <el-form-item prop="date1">
              <el-time-picker v-model="shop.openTime" format="HH:mm" value-format="HH:mm" :placeholder="$t('Morning')"
                              style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="1" class="line" align="center">-</el-col>
          <el-col :span="6">
            <el-form-item prop="date1">
              <el-time-picker v-model="shop.closeTime" format="HH:mm" value-format="HH:mm" :placeholder="$t('Night')"
                              style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item :label="$t('Store_introduction')" prop="description">
          <el-input v-model="shop.description" type="textarea" placeholder="" autosize />
        </el-form-item>-->
        <el-form-item :label="$t('Service_areas')" prop="range">
          <el-radio-group v-model="limited">
            <!--            <el-radio :label="false">{{$t('Not_limited_to_')}}</el-radio>-->
            <el-radio :label="true">{{ $t('Service_area_setting') }}{{ $t('(单位：MI)') }}</el-radio>
          </el-radio-group>
          <div class="block">
            <el-slider :min="1" :max="100" v-model="rangeMI" show-input>
            </el-slider>

          </div>
          <!--          <el-input v-show="limited" v-model.number="shop.range" :placeholder="$t('Service_area_setting')">
            <template slot="append">KM</template>
          </el-input>-->
        </el-form-item>

        <el-form-item prop="range">
          <el-radio-group v-model="limited">
            <!--            <el-radio :label="false">{{$t('Not_limited_to_')}}</el-radio>-->
            <el-radio :label="true">{{ $t('Service_area_setting') }}{{ $t('(单位：KM)') }}</el-radio>
          </el-radio-group>
          <div class="block">
            <el-slider :min="1" :max="161" v-model="shop.range" show-input>
            </el-slider>

          </div>
          <!--          <el-input v-show="limited" v-model="shop.range" :placeholder="$t('Service_area_setting')">
                      <template slot="append">KM</template>
                    </el-input>-->
        </el-form-item>
        <el-form-item :label="$t('时区')" prop="timeDifference">
          <el-select :style="{width: '500px'}" filterable  v-model="shop.timezone">
            <el-option
              v-for="item in timeZoneObject"
              :value="item.key"
              :label="$t(item.text)">
              <span style="float: left">{{ item.text }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.key }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('Order_type')" prop="types">
          <el-checkbox-group v-model="shop.types">
            <el-checkbox :label="1">{{ $t('Customer_self-serve') }}</el-checkbox>
            <el-checkbox :label="2">{{ $t('Supports_delivery') }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item :label="$t('Operation_Status')" prop="status">
          <el-tag>
            {{shop.status==1?$t('Open_for_business'):(shop.status==2?$t('Closed'):$t('Renovating'))}}
          </el-tag>
<!--          <el-select v-model="shop.status">
            <el-option :value="1" :label="$t('Open_for_business')" />
            <el-option :value="2" :label="$t('Closed')" />
            <el-option :value="3" :label="$t('Renovating')" />
          </el-select>-->
        </el-form-item>
      </el-form>
    </el-card>

    <div class="op-container" style="margin-top: 10px; ">
      <el-button @click="handleCancel">{{ $t('Cancel') }}</el-button>
      <el-button v-permission="['PUT /admin/shop/update']" type="primary" @click="handleEdit">{{ $t('Update_Store') }}
      </el-button>
    </div>

  </div>
</template>

<script>
import { detailShop, editShop } from '@/api/shop'
import { getShopkeeper, getShopManager, getShopMembers } from '@/api/admin'
import { listCountryRegion, listSubRegion } from '@/api/region'
import { MessageBox } from 'element-ui'
import { timeZoneObject } from './timezone.js';


export default {
  name: 'ShopEdit',
  data() {
    const validateService = (rule, value, callback) => {
      if (!this.shop.openTime || !this.shop.closeTime) {
        callback(new Error(this.$t('服务时间不能为空')))
      } else {
        callback()
      }
    }
    const validateCountry = (rule, value, callback) => {
      if (!this.regionIds || !this.regionIds[0]) {
        callback(new Error(this.$t('国家不能为空')))
      } else {
        callback()
      }
    }
    const validateProvince = (rule, value, callback) => {
      if (!this.regionIds || !this.regionIds[1]) {
        callback(new Error(this.$t('省份不能为空')))
      } else {
        callback()
      }
    }
    const validateCity = (rule, value, callback) => {
      if (!this.regionIds || !this.regionIds[2]) {
        callback(new Error(this.$t('城市不能为空')))
      } else {
        callback()
      }
    }
    const validateCounty = (rule, value, callback) => {
      if (!this.regionIds || !this.regionIds[3]) {
        callback(new Error(this.$t('区县不能为空')))
      } else {
        callback()
      }
    }

    const weeksTimeMap={
      1: this.$t('星期一'),
      2: this.$t('星期二'),
      3: this.$t('星期三'),
      4: this.$t('星期四'),
      5: this.$t('星期五'),
      6: this.$t('星期六'),
      7: this.$t('星期日')
    }

    return {
      weeksTimeMap,
      showDatepicker: false,
      selectedDate: new Date(),

      timeZoneObject,
      limited: true,
      weeksTime:[],
      special:[],

      shop: { types: [], weeks: [] ,timezone:'',timeDifference:'',weeksTime:[]},
      //门店欲自定义颜色
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)',
        '#c7158577'
      ],
      regionIds: [],
      shopManager: {},
      shopkeeper: {},
      shopMembers: [],
      countrys: [],
      provinces: [],
      citys: [],
      countys: [],
      rules: {
        /*        streetAddress: [
                  { required: true, message: this.$t('Store_address_cannot_be_empty'), trigger: 'blur' }
                ],*/
        name: [{ required: true, message: this.$t('Store_name_cannot_be_empty'), trigger: 'blur' }],
        // range: [{ type: 'number', message: '服务范围必须为数字', trigger: 'change' }],
        streetAddress: [
          { required: true, message: this.$t('Store_address_cannot_be_empty'), trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: this.$t('联系电话不能为空'), trigger: 'blur' },
        ],
        weeks: [
          { required: true, message: this.$t('服务星期不能为空'), trigger: 'blur' },
        ],
        types: [
          { required: true, message: this.$t('订单类型不能为空'), trigger: 'blur' },
        ],
        serviceTime: [
          // { required: true, message: this.$t('服务时间不能为空'), trigger: 'blur' },
          { validator: validateService, trigger: 'blur' }
        ],
        country: [
          { validator: validateCountry, trigger: 'blur' }
        ],
        province: [
          { validator: validateProvince, trigger: 'blur' }
        ],
        city: [
          { validator: validateCity, trigger: 'blur' }
        ],
        /*        county: [
                  { validator: validateCounty, trigger: 'blur' }
                ],*/
      }
    }
  },
  /*  computed: {
      limited() {
        if (this.shop.range > 0) {
          return true
        }
        return false
      }
    },*/
  computed: {
    rangeMI: {
      get: function () {
        return this.shop.range / 1.61
      },
      set: function (newValue) {
        this.shop.range = newValue * 1.61
      }
    }
  },
  created() {
    this.init()
    this.getCountrys()
  },
  methods: {
    init: function () {
      if (this.$route.query.id == null) {
        return
      }
      const shopId = this.$route.query.id
      detailShop(shopId).then(response => {
        this.shop = response.data.data
        this.shop.regions.forEach(region => {
          this.regionIds.push(region.id)
        })
        this.getPrivonces()
        this.getCitys()
        this.getCountys()
        if (this.shop.range) {
          this.limited = true
        }
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
      // 店长
      getShopkeeper(shopId).then(res => {
        if (res.data.data) {
          this.shopkeeper = res.data.data
        }
      }).catch(() => {

      })

      // 经理
      getShopManager(shopId).then(res => {
        if (res.data.data) {
          this.shopManager = res.data.data
        }
      }).catch(() => {

      })
      getShopMembers(shopId).then((res) => {
        this.shopMembers = res.data.data
      })
    },
    getCountrys() {
      listCountryRegion().then(response => {
        this.countrys = response.data.data.list
      })
    },
    getPrivonces(refresh) {
      let query = {
        id: this.regionIds[0],
        type: 1
      }
      if (refresh) {
        this.regionIds.splice(1, 1)
      }
      listSubRegion(query).then(response => {
        this.provinces = response.data.data.list
      })
    },
    getCitys(refresh) {
      let query = {
        id: this.regionIds[1],
        type: 2
      }
      if (refresh) {
        this.regionIds.splice(2, 1)
      }
      listSubRegion(query).then(response => {
        this.citys = response.data.data.list
      })
    },
    getCountys(refresh) {
      let query = {
        id: this.regionIds[2],
        type: 2
      }
      if (refresh) {
        this.regionIds.splice(3, 1)
      }
      listSubRegion(query).then(response => {
        this.countys = response.data.data.list
      })
    },
    handleCancel: function () {
      this.$router.push({ path: '/shop/list' })
    },
    handleEdit: function () {

      if(this.shop.weeksTime==undefined||this.shop.weeksTime.filter(item => item !== null).length!=7){
        this.$notify({
          title: '警告',
          message: '请完善周一至周日的服务时间！再继续...',
          type: 'warning'
        });
        return;
      }


      let shop = {
        litemallShop: this.shop,
        shopManagerId: this.shopManager.id || null,
        shopkeeperId: this.shopkeeper.id || null,
        regionIds: this.regionIds
      }

      this.$refs['shop'].validate(valid => {
        if (valid) {
          editShop(shop)
            .then(response => {
              this.$notify.success({
                title: this.$t('Success!'),
                message: this.$t('修改成功')
              })
              this.$router.push({ path: '/shop/list' })
            })
            .catch(response => {
              MessageBox.alert(this.$t('Error') + this.$t(response.data.errmsg), this.$t('Warning'), {
                confirmButtonText: this.$t('Confirm'),
                type: 'error'
              })
            })
        }
      })
    },
    members() {
      this.$router.push({ path: '/shop/admin', query: { shopId: this.shop.id } })
    },
    handleLogs() {
      this.$router.push({ path: '/shop/logs', query: { id: this.shop.id } })
    },
    showDatePicker() {
      this.showDatepicker = !this.showDatepicker;

    },
    //选择了某一天
    handleChangePicker(date){
      const newDate = { specialDate: date, specialTime: ['23:59:59','23:59:59'] };
      const hasDuplicate = this.special.some(item => item.specialDate === newDate.specialDate);
      if (!hasDuplicate) {
        this.special.push(newDate);
        this.special.sort((a, b) => {
          const dateA = new Date(a.specialDate);
          const dateB = new Date(b.specialDate);
          return dateA - dateB;
        });
      } else {
        // 如果存在相同的 specialDate 值，进行相应的处理
        this.$notify({
          title: '警告',
          message: '已存在相同的日期，无法添加重复项',
          type: 'warning'
        });
      }
    },
    handleSpecialTimeDeleted(index){
      this.special.splice(index, 1);
    },
    handleShow(){
      if(this.shop.weeksTime==null||this.shop.weeksTime==undefined){
        for (let i = 0; i < 7; i++) {this.weeksTime.push(['23:59:59', '23:59:59']);}
        this.shop.weeksTime=this.weeksTime
      }else {
        this.weeksTime=this.shop.weeksTime
      }
      this.special=this.shop.special
    }
  }
}
</script>
